#include "debug.h"
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <set>
#include <wx/msgdlg.h>
#include <wx/timer.h>

#define _CRT_SECURE_NO_WARNING

wxLongLong log_start_time;
wxLongLong log_last_time;
int log_nest_level=0;
FILE *log_file_handle;

#ifdef _DEBUG
std::map<const char *, std::set<void*> > inst;
void InstanceWatcherCheck()
{
    std::map<const char *, std::set<void*> >::iterator i;
    for (i=inst.begin(); i != inst.end(); i++) {
        wxString classname(i->first, wxConvLocal);
        std::set<void*>& instances = i->second;
        if (instances.size())
            wxMessageBox(wxString::Format("%d instances of %s not freed\n", instances.size(), classname), "Memory leak");
    }
}
#endif

void lognest()
{
    for (int i=0; i<log_nest_level; i++) {
        fputc(' ', log_file_handle);
        fputc(' ', log_file_handle);
    }
}


void init_log(const char* filename)
{
    log_start_time = wxGetLocalTimeMillis();
    log_file_handle = fopen(filename, "wt");
    if (!log_file_handle) {
        fprintf(stderr, "failed to create log file '%s': %s\n", filename, strerror(errno));
        exit(1);
    }
    log_last_time = wxGetLocalTimeMillis();
}

void close_log()
{
    fclose(log_file_handle);
}

void do_log(const wxString& msg)
{
    wxLongLong time = wxGetLocalTimeMillis();

    wxLongLong timediff =  time - log_start_time;
    wxLongLong lastdiff = time-log_last_time;

    // using LLVM, the wxLongLong for some reason isn't compiled using 'long long' type
    // so we have to use ToLong()
    const wchar_t *fmt = L"[%4lu.%03lu | %4lu] ";
    fwprintf(log_file_handle, fmt, timediff.ToLong()/1000, timediff.ToLong() % 1000, lastdiff.ToLong());

    fflush(log_file_handle);
    lognest();
    fputws(msg.wc_str(), log_file_handle);
    fflush(log_file_handle);

    log_last_time = wxGetLocalTimeMillis();
}

